package benny.ApkposStore.Activity;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.serial.SerialPort;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import benny.ApkposStore.R;
import benny.ApkposStore.R.string;
import benny.ApkposStore.Adapter.CailistAdapter;
import benny.ApkposStore.Adapter.CailistAdapter.Dishholder;
import benny.ApkposStore.Adapter.cookAdapter;
import benny.ApkposStore.Adapter.cookselectAdapter.Cookselectholder;
import benny.ApkposStore.Adapter.dishlistAdapter;
import benny.ApkposStore.Adapter.dishlistAdapter.Dishlistholder;
import benny.ApkposStore.Adapter.dishpotlistAdapter;
import benny.ApkposStore.Adapter.dishpotlistAdapter.Dishpotlistholder;
import benny.ApkposStore.Adapter.dishtype1Adapter;
import benny.ApkposStore.Adapter.dishtype1Adapter.Dishtypeholder1;
import benny.ApkposStore.Adapter.dishtype2Adapter;
import benny.ApkposStore.Adapter.dishtype2Adapter.Dishtypeholder2;
import benny.ApkposStore.db.ConfigDBHelper;
import benny.ApkposStore.db.DBHelper;
import benny.ApkposStore.model.DishNew;
import benny.ApkposStore.model.Dish_class;
import benny.ApkposStore.model.Make_tbl;
import benny.ApkposStore.model.OrderNew;
import benny.ApkposStore.model.View_dian;
import benny.ApkposStore.model.Zuoflist;
import benny.ApkposStore.utils.ApkConfigdbUntils;
import benny.ApkposStore.utils.ApkConstant;
import benny.ApkposStore.utils.ApkDbUntils;
import benny.ApkposStore.utils.ApkUntils;
import benny.ApkposStore.utils.Apkglobal;
import benny.ApkposStore.utils.Rotate3dAnimation;

public class DishordersActivity extends Activity {
	public static DishordersActivity Activitythis;
	private Button returnButton = null;
	private AutoCompleteTextView autosearch = null;
	private GridView dishtypeGridView1 = null;
	private GridView dishtypeGridView3 = null;
	private GridView dishtypeGridView4 = null;
	private GridView dishtypeGridView2 = null;
	private dishtype1Adapter dishtypeAdapter1 = null;
	private dishtype2Adapter dishtypeAdapter2 = null;
	private CailistAdapter cainameAdapter = null;
	private final int dishtypebtn_widthpx = 97;
	private final int dishtypeSpacing = 2;
	private int dishtypebtn_widthdp;
	private int dishtypeSpacingdip;
	private int dishtypeview_width1;// 大类Gridview的宽度
	private GridView dishGridView;
	private GridView dishGridView2;
	private int dish_heightpx = 80;
	private int dish_heightdip;
	private int verticalSpacingdp;
	private int verticalSpacing = 5;
	private int dishview_height;
	private int dishtypedown1 = -1;
	private int dishtypedown2 = -1;
	private float typestate1 = -1;
	private float typestate2 = -1;
	private ListView dishlistView;
	private ListView setupdishlistView;
	private SimpleAdapter dishAdapter = null;
	private SimpleAdapter SimpleAdapter1 = null;
	private SimpleAdapter SimpleAdapter2 = null;
	private SimpleAdapter dishSimpleAdapter = null;
	private dishlistAdapter dishlistAdapter = null;
	private Resources resources;
	private List<View_dian> cainamelist;
	private List<View_dian> searchlist;
	private List<DishNew> dishlist = null;
	private List<Dish_class> dishtypelist1;
	private List<Dish_class> dishtypelist2;
	private int dishlist_heightdip;
	private int dishlist_heightpx = 19;
	private int diahlistview_height;
	private EditText payedittext1;
	private EditText payedittext2;
	private EditText payedittext3;
	private EditText payedittext4;
	private ListAdapter menuAdapter;
	private GridView gridView;
	private int tagold = 0;
	// private View cookView = null;
	public static PopupWindow dishcookwin;
	public static PopupWindow cookwin;
	// private cookselectAdapter cookselectAdapter = null;
	private dishpotlistAdapter dishpotlistAdapter = null;
	// private int cooklist_heightdip;
	private int cooklistview_height;
	// private int cooklist_heightpx = 28;
	private int dishpotlist_heightpx = 25;
	private Button cookviewclose;
	private Button cookviewbtn1;
	private Button cookviewbtn2;
	private Button cookviewbtn3;
	private Button cookviewbtn4;
	private GridView powgridView;
	private EditText dishcountchange;
	private Button setup_dish;
	private View dishView;
	private PopupWindow setupdishwin;
	private int dishpotlist_heightdip;
	private String room_id = null;
	private String orderid;
	private String room_name;
	private int peoplenum;
	private EditText room_nametext;
	private EditText peoplenumtext;
	private TextView orderidtext;
	private SQLiteDatabase db;
	private SimpleDateFormat dateformat;
	private String dpriflo_now = "";
	private String dishnum_now = "";
	private String ddet_now = "";
	private TextView pay_xj;
	private TextView pay_zk;
	private TextView pay_ys;
	private TextView pay_zl;
	private float xiaoji;
	private float zhekou;
	private float yingshou;
	private float zhaolin;
	private float shishou;
	private int paytype1;
	private int paytype2;
	private int paytype3;
	private int rate1;
	private int rate2;
	private int rate3;
	private Button print_dish;
	private OutputStream os_start;
	private Socket socket = null;
	private boolean key_jiansuo = true;
	private Button search;
	private EditText autobarcode;
	private Button barcode;
	private int endterint = 0;
	private String endterstr = "";
	private ArrayList<OrderNew> orderlist;
	private OrderNew ordermain;
	private TextView username_text;
	private Button order_dish;
	private Button payment;
	private float extra_total;
	// private ListView cookselectListview;
	protected List<Make_tbl> maketbllist;
	protected List<Make_tbl> searchmaketbllist;
	protected List<Zuoflist> zuofselectllist;
	protected cookAdapter cooklistAdapter;
	protected SimpleAdapter cooksearchAdapter;
	// private float SL;
	private static final String HOST = "192.168.0.222";
	private static final int PORT = 9100;
	private Drawable mIconSearchDefault;
	private Drawable mIconSearchClear;
	private boolean keydown = false;
	// ///////////////////打印指令
	static byte[] print_1BC = { 0x1B, 0x21, 0x18 };// 1倍加大加粗
	static byte[] print_3BCM = { 0x1C, 0x21, 0x0C, 0x1B, 0x21, 0x30, 0x1B,
			0x61, 0x31 };// 3倍加大加粗居中
	static byte[] print_M = { 0x1B, 0x61, 0x31 };// 居中
	static byte[] print_2B = { 0x1D, 0x21, 0x01 };// 2倍加大
	static byte[] print_2BM = { 0x1D, 0x21, 0x01, 0x1B, 0x61, 0x31 };// 2倍加大
	static byte[] print_2BD = { 0x1D, 0x21, 0x10 };// 2倍加大扁型
	static byte[] print_3B = { 0x1C, 0x21, 0x0C, 0x1B, 0x21, 0x30 };// 3倍加大加粗
	static byte[] print_BEGIN = { 0x1B, 0x40 };// 恢复指令
	static byte[] print_CUT = { 0x1D, 0x56, 0x1, 0x0 };// 切刀
	static byte[] print_ENTER = { 0x0D, 0x0A }; // 换行
	private SQLiteDatabase configdb;
	private int price_type;
	public String tag = "DishordersActivity";
	private TextView pay_ss;
	private TextView pay_type1;
	private TextView pay_type2;
	private TextView pay_type3;
	static HashMap<String, String> print_map = null;
	static HashMap<String, String> pay_map = null;
	static Context mcx = null;

	// ////////////////////////////

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ApkUntils.fullscreen(this);
		setContentView(R.layout.dishorders);
		keydown = false;	
		mcx=this;
		resources = getResources();
		mIconSearchDefault = resources
				.getDrawable(R.drawable.txt_search_default);
		mIconSearchClear = resources.getDrawable(R.drawable.txt_search_clear);
		dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Activitythis = this;
		Intent intent = getIntent();
		Bundle bd = intent.getExtras();// 根据bundle的key得到对应的对象
		room_name = bd.getString("room_name");
		room_id = bd.getString("room_id");
		orderid = bd.getString("orderid");
		peoplenum = bd.getInt("people_num");
		price_type = bd.getInt("price_type");
		search = (Button) findViewById(R.id.search);
		search.setTag(1);
		search.setOnClickListener(new searchButtonListener());
		barcode = (Button) findViewById(R.id.barcode);
		barcode.setTag(2);
		barcode.setOnClickListener(new searchButtonListener());
		autobarcode = (EditText) findViewById(R.id.autobarcode);
		username_text = (TextView) findViewById(R.id.username_text);
		username_text.setText(Apkglobal.getrealname());
		returnButton = (Button) findViewById(R.id.Return);
		returnButton.setOnClickListener(new returnButtonListener());
		menuAdapter = ApkUntils.getMenuAdapter(this);

		if (Apkglobal.getpay_map() != null) {
			pay_map = Apkglobal.getpay_map();
		} else {
			pay_map = ApkConfigdbUntils.getpay_map(configdb,
					getApplicationContext());
			Apkglobal.setpay_map(pay_map);
		}
		// ////生成大类布局

		dishtypeGridView3 = (GridView) findViewById(R.id.dishtypeGridView3);
		dishtypebtn_widthdp = ApkUntils.convertPX2DIP(this, dishtypebtn_widthpx
				* ApkUntils.getPixelsintW(this));
		dishtypeSpacingdip = ApkUntils.convertPX2DIP(this, dishtypeSpacing
				* ApkUntils.getPixelsintH(this));
		dishtypeGridView3.setColumnWidth(dishtypebtn_widthdp);
		dishtypeGridView3.setHorizontalSpacing(dishtypeSpacingdip);
		dishtypeGridView3.setGravity(Gravity.CENTER);
		dishtypeGridView3.setSelector(R.color.transparent);
		dishtypeGridView1 = (GridView) findViewById(R.id.dishtypeGridView1);
		dishtypebtn_widthdp = ApkUntils
				.convertPX2DIP(this, dishtypebtn_widthpx);
		dishtypeSpacingdip = ApkUntils.convertPX2DIP(this, dishtypeSpacing
				* ApkUntils.getPixelsintH(this));
		dishtypeGridView1.setColumnWidth(dishtypebtn_widthdp);
		dishtypeGridView1.setHorizontalSpacing(dishtypeSpacingdip);
		dishtypeGridView1.setGravity(Gravity.CENTER);
		dishtypeGridView1.setSelector(R.color.transparent);
		dishtypeGridView1.setOnItemClickListener(new firstdishtypeListener());
		// /////////////////////////////////////////////////////

		// ////生成小类布局

		dishtypeGridView4 = (GridView) findViewById(R.id.dishtypeGridView4);
		dishtypebtn_widthdp = ApkUntils
				.convertPX2DIP(this, dishtypebtn_widthpx);
		dishtypeSpacingdip = ApkUntils.convertPX2DIP(this, dishtypeSpacing);
		dishtypeGridView4.setColumnWidth(dishtypebtn_widthdp);
		dishtypeGridView4.setHorizontalSpacing(dishtypeSpacingdip);
		dishtypeGridView4.setGravity(Gravity.CENTER);
		dishtypeGridView4.setSelector(R.color.transparent);
		dishtypeGridView2 = (GridView) findViewById(R.id.dishtypeGridView2);
		dishtypebtn_widthdp = ApkUntils
				.convertPX2DIP(this, dishtypebtn_widthpx);
		dishtypeSpacingdip = ApkUntils.convertPX2DIP(this, dishtypeSpacing);
		dishtypeGridView2.setColumnWidth(dishtypebtn_widthdp);
		dishtypeGridView2.setHorizontalSpacing(dishtypeSpacingdip);
		dishtypeGridView2.setGravity(Gravity.CENTER);
		dishtypeGridView2.setSelector(R.color.transparent);
		dishtypeGridView2.setOnItemClickListener(new seconddishtypeListener());
		// /////////////////////////////////////////////////////

		// ////生成菜品区布局

		dishGridView2 = (GridView) findViewById(R.id.dishGridView2);
		dish_heightdip = ApkUntils.convertPX2DIP(this, dish_heightpx);
		verticalSpacingdp = ApkUntils.convertPX2DIP(this, verticalSpacing);
		dishGridView2.setNumColumns(5);
		dishGridView2.setPadding(2, 0, 0, 0);
		dishGridView2.setGravity(Gravity.FILL_VERTICAL);
		dishGridView2.setSelector(R.color.transparent);
		dishGridView2.setVerticalSpacing(verticalSpacingdp);

		dishGridView = (GridView) findViewById(R.id.dishGridView);
		dish_heightdip = ApkUntils.convertPX2DIP(this, dish_heightpx);
		verticalSpacingdp = ApkUntils.convertPX2DIP(this, verticalSpacing);
		dishGridView.setNumColumns(5);
		dishGridView.setPadding(2, 0, 0, 0);
		dishGridView.setGravity(Gravity.FILL_VERTICAL);
		dishGridView.setSelector(R.color.transparent);
		dishGridView.setVerticalSpacing(verticalSpacingdp);
		dishGridView.setOnItemClickListener(new cainameListener());
		// /////////////////////////////////////////////////////

		// 绑定搜索框autosearch事件
		autosearch = (AutoCompleteTextView) findViewById(R.id.autosearch);
		// autosearch.setInputType(InputType.TYPE_NULL);
		autosearch.setOnKeyListener(new autosearchOnkeyListener());
		autosearch.setThreshold(1);
		autosearch.setHint("请输入菜品名或检索码");
		// autosearch.setCompoundDrawablesWithIntrinsicBounds(null,
		// null, null, null);
		autosearch.setOnItemClickListener(new autosearchItemClickListener());
		autosearch.setOnTouchListener(new autosearchOnTouchListener());
		// autosearch.setOnItemSelectedListener(new
		// autosearchselectClickListener());
		autosearch.addTextChangedListener(new TextWatcher() {
			// 缓存上一次文本框内是否为空
			private boolean isnull = true;

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				autosearch.setThreshold(1);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (TextUtils.isEmpty(s)) {
					if (!isnull) {
						autosearch.setCompoundDrawablesWithIntrinsicBounds(
								null, null, null, null);
						isnull = true;
					}
				} else {
					if (isnull) {
						autosearch.setCompoundDrawablesWithIntrinsicBounds(
								null, null, mIconSearchClear, null);
						isnull = false;
					}
				}

			}
		});

		// // 显示点菜列表
		pay_xj = (TextView) findViewById(R.id.paytext1);
		pay_zk = (TextView) findViewById(R.id.paytext3);
		pay_ys = (TextView) findViewById(R.id.paytext5);
		pay_zl = (TextView) findViewById(R.id.paytext7);
		pay_ss = (TextView) findViewById(R.id.paytitle2);
		pay_type1 = (TextView) findViewById(R.id.paytitle4);
		pay_type2 = (TextView) findViewById(R.id.paytitle6);
		pay_type3 = (TextView) findViewById(R.id.paytitle8);
		String title = pay_map.get("1").toString();
		String rate = pay_map.get("1R").toString();
		if (!title.equals("")) {
			pay_type1.setText(title);
			pay_type1.setHint(rate);
			rate1=Integer.parseInt(rate);
		
		}
		else {
			rate1=100;
		}
		
		title = pay_map.get("2").toString();
		rate = pay_map.get("2R").toString();
		if (!title.equals("")) {
			pay_type2.setText(title);
			pay_type2.setHint(rate);
			rate2=Integer.parseInt(rate);
		}
		else {
			rate2=100;
		}
		title = pay_map.get("3").toString();
		rate = pay_map.get("3R").toString();
		if (!title.equals("")) {
			pay_type3.setText(title);
			pay_type3.setHint(rate);
			rate3=Integer.parseInt(rate);
		}
		else {
			rate3=100;
		}

		payedittext1 = (EditText) findViewById(R.id.payeditText1);
		payedittext2 = (EditText) findViewById(R.id.payeditText2);
		payedittext3 = (EditText) findViewById(R.id.payeditText3);
		payedittext4 = (EditText) findViewById(R.id.payeditText4);
		payedittext1.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				payedittext1.setHint(payedittext1.getText().toString());
				payedittext2.setHint(payedittext2.getText().toString());
				payedittext3.setHint(payedittext3.getText().toString());
				payedittext4.setHint(payedittext4.getText().toString());

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (TextUtils.isEmpty(s)) {
					payedittext1.setHint("0.0");
				}
				else {
					payedittext1.setHint(payedittext1.getText().toString());
				}
				zhaolin = Float.parseFloat(payedittext2.getHint().toString())
						+ Float.parseFloat(payedittext3.getHint().toString())
				        + Float.parseFloat(payedittext4.getHint().toString())
				        - Float.parseFloat(payedittext1.getText().toString());
				pay_zl.setText(ApkUntils.convertFloat(zhaolin + "",
						ApkConstant.FLOAT_NUM));

			}
		});
		payedittext2.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				payedittext1.setHint(payedittext1.getText().toString());
				payedittext2.setHint(payedittext2.getText().toString());
				payedittext3.setHint(payedittext3.getText().toString());
				payedittext4.setHint(payedittext4.getText().toString());

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (TextUtils.isEmpty(s)) {
					payedittext2.setHint("0.0");
				}
				else {
					payedittext2.setHint(payedittext2.getText().toString());
				}
				zhaolin = Float.parseFloat(payedittext2.getHint().toString())
						+ Float.parseFloat(payedittext3.getHint().toString())
				        + Float.parseFloat(payedittext4.getHint().toString())
						- Float.parseFloat(payedittext1.getHint().toString());
				pay_zl.setText(ApkUntils.convertFloat(zhaolin + "",
						ApkConstant.FLOAT_NUM));
			}
		});
		payedittext3.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				payedittext1.setHint(payedittext1.getText().toString());
				payedittext2.setHint(payedittext2.getText().toString());
				payedittext3.setHint(payedittext3.getText().toString());
				payedittext4.setHint(payedittext4.getText().toString());
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (TextUtils.isEmpty(s)) {
					payedittext3.setHint("0.0");
				}else {
					payedittext3.setHint(payedittext3.getText().toString());
				}

				shishou = Float.parseFloat(payedittext1.getHint().toString());
				payedittext1.setText(ApkUntils.convertFloat(shishou + "",
						ApkConstant.FLOAT_NUM));
				zhaolin = Float.parseFloat(payedittext2.getHint().toString())
						+ Float.parseFloat(payedittext3.getHint().toString())
						 + Float.parseFloat(payedittext4.getHint().toString())
						- shishou;
				pay_zl.setText(ApkUntils.convertFloat(zhaolin + "",
						ApkConstant.FLOAT_NUM));
			}
		});
		payedittext4.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				payedittext1.setHint(payedittext1.getText().toString());
				payedittext2.setHint(payedittext2.getText().toString());
				payedittext3.setHint(payedittext3.getText().toString());
				payedittext4.setHint(payedittext4.getText().toString());
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (TextUtils.isEmpty(s)) {
					payedittext4.setHint("0.0");
				}else {
					payedittext4.setHint(payedittext4.getText().toString());
				}

				shishou = Float.parseFloat(payedittext1.getHint().toString());
				payedittext1.setText(ApkUntils.convertFloat(shishou + "",
						ApkConstant.FLOAT_NUM));
				zhaolin = Float.parseFloat(payedittext2.getHint().toString())
						+ Float.parseFloat(payedittext3.getHint().toString())
						 + Float.parseFloat(payedittext4.getHint().toString())
						- shishou;
				pay_zl.setText(ApkUntils.convertFloat(zhaolin + "",
						ApkConstant.FLOAT_NUM));
			}
		});
		dishlistView = (ListView) findViewById(R.id.dishListview);
		dishlistView.setDrawSelectorOnTop(false);
		dishlistView.setBackgroundColor(R.color.grid_line);
		dishlistView.setSelector(R.color.transparent);
		// resources = getResources();
		dishlistView.setDivider(resources.getDrawable(R.color.grid_line));
		dishlistView.setDividerHeight(ApkUntils.convertPX2DIP(this, 1));
		dishlist_heightdip = ApkUntils.convertPX2DIP(this, dishlist_heightpx);
		// showdishlist();
		dishlistView.setOnItemLongClickListener(new dishlistItemLongListener());

		// //////////////埋单区
		gridView = (GridView) this.findViewById(R.id.gridview_softkeyboard);
		payedittext1.setTag(1);
		payedittext1.setOnTouchListener(new payEdittextTouchListener());
		payedittext2.setTag(2);
		payedittext2.setOnTouchListener(new payEdittextTouchListener());
		payedittext3.setTag(3);
		payedittext3.setOnTouchListener(new payEdittextTouchListener());
		payedittext4.setTag(4);
		payedittext4.setOnTouchListener(new payEdittextTouchListener());

		payedittext1.setInputType(InputType.TYPE_NULL);
		payedittext2.setInputType(InputType.TYPE_NULL);
		payedittext3.setInputType(InputType.TYPE_NULL);
		payedittext4.setInputType(InputType.TYPE_NULL);
		// //////修改桌台号和人数
		room_nametext = (EditText) findViewById(R.id.roomname);
		peoplenumtext = (EditText) findViewById(R.id.peoplenum);
		orderidtext = (TextView) findViewById(R.id.orderid);
		room_nametext.setText(room_name);
		room_nametext.setHint(room_id);
		orderidtext.setText("NO." + orderid);
		orderidtext.setHint(orderid);
		peoplenumtext.setText(peoplenum + "");
		room_nametext.setInputType(InputType.TYPE_NULL);
		peoplenumtext.setInputType(InputType.TYPE_NULL);
		room_nametext.setTag(5);
		room_nametext.setOnTouchListener(new payEdittextTouchListener());
		peoplenumtext.setTag(6);
		peoplenumtext.setOnTouchListener(new payEdittextTouchListener());
		// //////显示菜品扩展
		setup_dish = (Button) findViewById(R.id.setup_dish);
		setup_dish.setOnClickListener(new setup_dishListener());
		// //////打单按钮
		print_dish = (Button) findViewById(R.id.print_dish);
		print_dish.setOnClickListener(new print_dishListener());
		// //////落单按钮
		order_dish = (Button) findViewById(R.id.order_dish);
		order_dish.setOnClickListener(new order_dishListener());
		// //////结账按钮
		payment = (Button) findViewById(R.id.payment);
		payment.setOnClickListener(new paymentListener());
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		return super.onKeyDown(keyCode, event);
	}

	// 创建菜品扩展按钮Listener
	class setup_dishListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			//

			// showsetupdishWindow(v);
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString("orderid", orderid);
			bundle.putString("room_name", room_name);
			bundle.putString("room_id", room_id);
			bundle.putInt("people_num", peoplenum);
			intent.putExtras(bundle);
			intent.setClass(DishordersActivity.this, SetupdishActivity.class);
			startActivity(intent);

		}

	}

	// 创建落单按钮Listener
	class order_dishListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			if (keydown) {
				return;
			}

				try {
					keydown = true;
					orderdishs(orderid, "传菜");
					showdishlist();
					keydown = false;
				} catch (Exception e) {
					// TODO: handle exception
					keydown = false;
				}

			}

	}

	// 创建结账按钮Listener
	class paymentListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			 if (keydown) {
				return;
			}

				try {
					keydown = true;
					String date = dateformat.format(new java.util.Date());
					String order_pay = Float.parseFloat(payedittext1.getHint()
							.toString()) * 100 + "";
					String dic = Float.parseFloat(pay_zk.getText().toString())
							* 100 + "";
					String extra = ApkUntils.convertFloat(extra_total * 100
							+ "", ApkConstant.FLOAT_NUM);
					String dish_total = (Float.parseFloat(pay_xj.getText()
							.toString()))* 100 + "";
					
                    paytype1=(int) (Float.parseFloat(payedittext2.getHint()
        							.toString()) -zhaolin) * 100;
                
                    paytype2=(int) (Float.parseFloat(payedittext3.getHint()
                    		.toString()) * 100);
                   
                    paytype3=(int) (Float.parseFloat(payedittext4.getHint()
                    		.toString()) * 100);
         
					paybill(orderid, dish_total, date, order_pay, dic, "0",
							"0", extra, Apkglobal.getrealname());
					keydown = false;
				} catch (Exception e) {
					keydown = false;
					Log.e(tag, e.getMessage());
				}
		}
	}

	// 异步打印任务
	private class AsyncPrintbill extends AsyncTask<Void, Void, Integer> {
		private String billid = "";
		private int print_mode = 1;
		private int msg_int = 0;
		private String msg = "打印失败，请重新尝试！";

		public void setOrderid(String id) {
			billid = id;
		}

		public void setPrint_mode(int mode) {
			print_mode = mode;
		}

		@Override
		protected Integer doInBackground(Void... params) {

			try {
				if (print_mode == 0) {
					SerialPort sp_start = new SerialPort(
							new File("/dev/ttyS2"), 9600);// ttyS2
					os_start = sp_start.getOutputStream();
					printbill(billid, "结算单");
					sp_start.close();
				} else {

					try {
						socket = new Socket(HOST, PORT);
					} catch (IOException e) {
						e.printStackTrace();
						msg = "打印失败!网络异常！";
						Log.e("Socket exception: ", e.getMessage());
						return -1;
					}

					if (socket.isConnected()) {
						if (!socket.isOutputShutdown()) {
							os_start = socket.getOutputStream();
							msg_int = printbill(billid, "结算单");
							if (msg_int > 0) {
								if (msg_int == 1) {
									msg = "还有菜品没有落单，无法打单！";
								} else {
									msg = "当前没有菜品，无需打单！";
								}
								return msg_int;
							}

						}
						socket.close();
					}

					// new Thread(new SocketClient()).start();
				}

				return 0;
			} catch (Exception e) {
				Log.e(tag, "AsyncPrintbill:" + e.getMessage());
				msg = "打印失败！" + e.getMessage();

			}

			return -1;
		}

		// 在doInBackground前执行
		protected void onPreExecute() {
			// TODO: 显示正在登陆的提示

		}

		// 在doInBackground后执行
		protected void onPostExecute(Integer result) {

			if (result == 0) {
				// login ok

				try {
					String sql = "update apkpos_orders_new set room_state=6 where orderid='"
							+ orderid + "'";
					execSQL(db,mcx,sql);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				
				return;

			} else {
				// TODO: login failed，取消正在登陆的提示，换成提示登陆失败
				Toast.makeText(DishordersActivity.this, msg, Toast.LENGTH_SHORT)
						.show();
			}
		}
	}
	


	// 创建菜品扩展按钮Listener
	class print_dishListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
            if (keydown) {
				return;
			}
				keydown = true;
				try {

					AsyncPrintbill asyncprintbill = new AsyncPrintbill();
					asyncprintbill.setPrint_mode(ApkConstant.PRINT_MODE);
					asyncprintbill.setOrderid(orderid);
					asyncprintbill.execute();

					// if (ApkConstant.PRINT_MODE == 0) {
					// SerialPort sp_start = new SerialPort(new File(
					// "/dev/ttyS2"), 19200);// ttyS2
					// os_start = sp_start.getOutputStream();
					// printbill(orderid, "结算单");
					// sp_start.close();
					// } else {
					//
					// try {
					// socket = new Socket(HOST, PORT);
					// } catch (IOException ex) {
					// ex.printStackTrace();
					// Log.e("Socket exception: ", ex.getMessage());
					// }
					//
					// if (socket.isConnected()) {
					// if (!socket.isOutputShutdown()) {
					// os_start = socket.getOutputStream();
					// printbill(orderid, "结算单");
					//
					// }
					// socket.close();
					// }
					//
					// // new Thread(new SocketClient()).start();
					// }
					keydown = false;
				} catch (Exception e) {
					System.out.println("print error" + e.getMessage());
					keydown = false;
				}
		}

	}

	public int printbill(String orderid, String billtype) {
		try {
			ordermain = ApkDbUntils.queryorder(db, getApplicationContext(),
					orderid);
			String aaa = "";

			if (db == null || !db.isOpen()) {
				db = DBHelper.getDatabase(getApplicationContext(), 0);
			}
			Cursor cursor = db
					.query("apkpos_orders_dishs",
							new String[] { "dish_id,dnam_var,dish_num,dish_price,dish_unit,order_mode,cook_extra,cook_content" },
							"orderid=? and order_state=0",
							new String[] { orderid }, null, null, null);
			int caiint = cursor.getCount();
			if (caiint > 0) {
				// Toast.makeText(this, "还有菜品没有落单，无法打单！", Toast.LENGTH_SHORT)
				// .show();
				return 1;
			}

			cursor = db
					.query("apkpos_orders_dishs",
							new String[] { "dish_id,dnam_var,dish_num,dish_price,dish_unit,order_mode,cook_extra,cook_content" },
							"orderid=?", new String[] { orderid }, null, null,
							null);
			caiint = cursor.getCount();
			if (caiint <= 0) {
				// Toast.makeText(this, "当前没有菜品，无需打单！", Toast.LENGTH_SHORT)
				// .show();
				return 2;
			}

			if (billtype != null) {
				aaa = Apkglobal.getshopname() + "(" + billtype + ")";
			} else {
				aaa = Apkglobal.getshopname();
			}
			printline(os_start, 0, aaa, print_2BM, print_ENTER);
			String str = ordermain.getOpen_time();
			String newStr = str.substring(str.indexOf(" ") + 1, str.length());
			aaa = "就餐时间 " + newStr;
			printline(os_start, 1, aaa, null, print_ENTER);
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			String date = sdf.format(new java.util.Date());
			aaa = "打印时间 " + date;
			printline(os_start, 0, aaa, null, print_ENTER);
			aaa = "流 水 号 " + orderid;
			printline(os_start, 0, aaa, null, print_ENTER);
			aaa = "收 银 员 " + Apkglobal.getrealname();
			printline(os_start, 0, aaa, null, print_ENTER);
			aaa = "";
			for (int i = 0; i < 45; i++) {
				aaa = aaa + "-";
			}
			printline(os_start, 0, aaa, null, print_ENTER);
			aaa = " 品名                 份量    单价   金额";
			printline(os_start, 0, aaa, null, print_ENTER);
			aaa = "";
			for (int i = 0; i < 45; i++) {
				aaa = aaa + "-";
			}
			printline(os_start, 0, aaa, null, print_ENTER);

			float num = 0;
			while (cursor.moveToNext()) {
				String dnam_var = cursor.getString(cursor
						.getColumnIndex("dnam_var"));
				float dish_num = cursor.getFloat(cursor
						.getColumnIndex("dish_num"));
				float dish_price = (float) (cursor.getFloat(cursor
						.getColumnIndex("dish_price")) * 0.01);
				float cook_extra = (float) (cursor.getFloat(cursor
						.getColumnIndex("cook_extra")) * 0.01);
				String dish_unit = cursor.getString(cursor
						.getColumnIndex("dish_unit"));
				String cook_content = cursor.getString(cursor
						.getColumnIndex("cook_content"));
				num = num + dish_num;
				if (cook_content == null) {
					aaa = dnam_var;
				} else {
					aaa = dnam_var + cook_content;
				}

				aaa = lengthstr(aaa, " ", 22, 1);
				aaa = aaa + ApkUntils.convertFloat(dish_num + "", 1)
						+ dish_unit;
				aaa = lengthstr(aaa, " ", 30, 1);
				aaa = aaa + ApkUntils.convertFloat(dish_price + "", 1);
				aaa = lengthstr(aaa, " ", 36, 1);
				aaa = aaa
						+ ApkUntils.convertFloat(
								(dish_price * dish_num + cook_extra) + "", 1);
				aaa = lengthstr(aaa, " ", 44, 1);
				printline(os_start, 0, aaa, null, print_ENTER);
			}
			aaa = "";
			for (int i = 0; i < 45; i++) {
				aaa = aaa + "-";
			}
			printline(os_start, 0, aaa, null, print_ENTER);
			aaa = "共计"
					+ lengthstr(ApkUntils.convertFloat(num + "", 1) + " 份",
							" ", 14, 0);
			aaa = aaa + " 实收"
					+ lengthstr(payedittext1.getText() + " 元", " ", 14, 0);
			printline(os_start, 0, aaa, null, print_ENTER);
			aaa = "收到" + lengthstr(payedittext2.getText() + " 元", " ", 14, 0);
			aaa = aaa + " 找零" + lengthstr(pay_zl.getText() + " 元", " ", 14, 0);
			printline(os_start, 0, aaa, null, print_ENTER);
			printline(os_start, 0, "地址：" + ApkConstant.ADDR, null, print_ENTER);

			// printline(os_start, aaa, print_2BM, print_ENTER);
			for (int i = 0; i < 4; i++) {
				os_start.write(print_ENTER);
			}

			os_start.write(print_CUT);
			cursor.close();

		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}

		return 0;

	}

	private String lengthstr(String str, String flag, int length, int state) {

		try {
			if (state == 1) {
				while (str.getBytes("GB18030").length < length) {
					str = str + flag;
				}
			} else {
				while (str.getBytes("GB18030").length < length) {
					str = flag + str;
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}

	public void printline(OutputStream out, int flag, String ss, byte[] start,
			byte[] end) {

		try {
			if (flag == 1) {
				out.write(print_BEGIN);
			}
			if (start != null) {

				out.write(start);
			}

			byte[] dd = ss.getBytes("gbk");
			out.write(dd);
			if (end != null) {
				out.write(end);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	// 创建大类状态Listener
	class dishlistItemLongListener implements OnItemLongClickListener {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub

			Dishlistholder holder = (Dishlistholder) arg1.getTag();
			// showcookviewWindow(arg1, holder);
			String dish_id = holder.dishitem1.getText().toString();
			String cooktitle = "菜名：" + holder.dishitem2.getText().toString();

			dpriflo_now = holder.dishitem5.getText().toString();
			dishnum_now = holder.dishitem3.getText().toString();
			ddet_now = holder.dishitem4.getText().toString();
			String dishpricestr = holder.dishitem5.getText() + "元×"
					+ holder.dishitem3.getText() + holder.dishitem4.getText()
					+ "=" + holder.dishtotal + "元";
			String countchange = holder.dishcount + "";
			String ordertype = holder.dishitem6.getText().toString();
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString("orderid", orderid);
			bundle.putString("dish_id", dish_id);
			bundle.putString("room_name", room_name);
			bundle.putString("room_id", room_id);
			bundle.putInt("people_num", peoplenum);
			bundle.putString("cooktitle", cooktitle);
			bundle.putString("dpriflo_now", dpriflo_now);
			bundle.putString("dishnum_now", dishnum_now);
			bundle.putString("ddet_now", ddet_now);
			bundle.putString("dishpricestr", dishpricestr);
			bundle.putString("countchange", countchange);
			bundle.putString("ordertype", ordertype);

			intent.putExtras(bundle);
			intent.setClass(DishordersActivity.this, ZuofActivity.class);
			startActivity(intent);
			// startActivity(new Intent(getApplicationContext(),
			// ZuofActivity.class));
			return false;
		}

	}

	// 创建可修改金额控件按下的Listener
	class payEdittextTouchListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			int tag = (Integer) v.getTag();
			EditText[] texts = { payedittext1, payedittext2, payedittext3,
					payedittext4, room_nametext, peoplenumtext };
			EditText vv = null;

			vv = texts[tag - 1];

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				vv.selectAll();

				break;
			case MotionEvent.ACTION_UP:

				if (tag > 4) {
					ApkUntils.changeviewlayoutMargin(gridView, 485, 0, 0, 0);
				} else {
					ApkUntils.changeviewlayoutMargin(gridView, 530, 0, 0, 0);
				}
				ApkUntils.opensoftkeyboard(vv, gridView, menuAdapter, 1);
				if (gridView.getVisibility() == View.INVISIBLE) {
					// ApkUntils.ViewVisible(gridView);
					Animation animation1 = AnimationUtils.loadAnimation(
							getApplicationContext(), R.anim.scale_translate_in);
					gridView.setAnimation(animation1);
					gridView.setVisibility(View.VISIBLE);
					vv.setFocusable(true);
					vv.setFocusableInTouchMode(true);
					vv.requestFocus();

				} else {
					if (tagold == tag) {
						// vv.setFocusable(false);
						ApkUntils
								.opensoftkeyboard(vv, gridView, menuAdapter, 0);
					}
					// if (tagold == tag) {
					// Animation animation2 = AnimationUtils.loadAnimation(
					// getApplicationContext(),
					// R.anim.scale_translate_out);
					// gridView.setAnimation(animation2);
					// gridView.setVisibility(View.INVISIBLE);
					// vv.setFocusable(false);
					// // ApkUntils.ViewInvisible(gridView);
					//
					// }

				}

				tagold = tag;
				break;
			default:
				break;
			}

			return false;
		}

	}

	private void showsetupdishlist(int flag) {
		updatedishlist();
		dishpotlistAdapter = new dishpotlistAdapter(this, dishlist);
		if (Apkglobal.getcurrentapiVersion() > 10) {
			setupdishlistView.setAdapter(dishpotlistAdapter);
		}
		if (flag == 1) {
			if (dishpotlistAdapter.getCount() == 0) {
				ApkUntils.changeviewlayout(setupdishlistView, 0, 1,
						dishpotlistAdapter);
			} else {
				cooklistview_height = dishpotlist_heightdip
						* dishpotlistAdapter.getCount();
				ApkUntils.changeviewlayout(setupdishlistView, 0,
						cooklistview_height, dishpotlistAdapter);
			}
		}

	}

	// 弹出扩展菜品操作窗口
	@SuppressWarnings("unused")
	private void showsetupdishWindow(View parent) {

		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		dishView = layoutInflater.inflate(R.layout.dishview, null);
		TextView roomname = (TextView) dishView.findViewById(R.id.roomtext);
		TextView people = (TextView) dishView.findViewById(R.id.peoplenumtext);
		TextView ordersid = (TextView) dishView.findViewById(R.id.ordersid);
		roomname.setText(room_name);
		ordersid.setText("NO." + orderid);
		people.setText(peoplenum + "");
		setupdishlistView = (ListView) dishView
				.findViewById(R.id.setupdishlistview);

		dishpotlist_heightdip = ApkUntils.convertPX2DIP(
				DishordersActivity.this, dishpotlist_heightpx);
		resources = getResources();
		setupdishlistView.setDivider(resources.getDrawable(R.color.white));
		setupdishlistView.setDividerHeight(ApkUntils.convertPX2DIP(
				DishordersActivity.this, 1));
		// setupdishlistView.setAdapter(dishpotlistAdapter);
		setupdishlistView.setSelector(R.color.transparent);
		// setupdishlistView.setOnItemClickListener();
		// 加载数据
		showsetupdishlist(1);
		setupdishlistView
				.setOnItemClickListener(new setupdishlistViewListener());
		cookviewclose = (Button) dishView.findViewById(R.id.cookviewclose); // 取得组件
		cookviewclose.setTag(10);
		cookviewbtn1 = (Button) dishView.findViewById(R.id.cookviewbtn1); // 取得组件
		cookviewbtn1.setTag(1);
		cookviewbtn2 = (Button) dishView.findViewById(R.id.cookviewbtn2); // 取得组件
		cookviewbtn2.setTag(2);
		cookviewbtn3 = (Button) dishView.findViewById(R.id.cookviewbtn3); // 取得组件
		cookviewbtn3.setTag(3);
		cookviewbtn4 = (Button) dishView.findViewById(R.id.cookviewbtn4); // 取得组件
		cookviewbtn4.setTag(4);
		cookviewbtn1.setOnClickListener(new dishbtnListener());
		cookviewbtn2.setOnClickListener(new dishbtnListener());
		cookviewbtn3.setOnClickListener(new dishbtnListener());
		cookviewbtn4.setOnClickListener(new dishbtnListener());
		cookviewclose.setOnClickListener(new dishbtnListener());

		powgridView = (GridView) dishView
				.findViewById(R.id.gridview_softkeyboard);
		dishcountchange = (EditText) dishView
				.findViewById(R.id.dishcountchange);
		ordermain = ApkDbUntils
				.queryorder(db, getApplicationContext(), orderid);
		dishcountchange.setText(ordermain.getDic_rate() + "");
		dishcountchange.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					dishcountchange.selectAll();
					break;
				case MotionEvent.ACTION_UP:

					ApkUntils.opensoftkeyboard(dishcountchange, powgridView,
							menuAdapter, 1);
					ApkUntils.keyboardtouchup(dishcountchange, powgridView,
							menuAdapter, getApplicationContext());

					break;
				default:
					break;
				}

				return false;
			}
		});

		dishcountchange.setTag(1);
		dishcountchange.setInputType(InputType.TYPE_NULL);

		// // 创建一个PopuWidow对象
		if (setupdishwin == null) {
			setupdishwin = new PopupWindow(dishView, LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT, true);
			// setupdishwin.setAnimationStyle(R.anim.push_up_in);
			// 上下进入
			setupdishwin
					.setAnimationStyle(android.R.style.Animation_InputMethod);
			// 右向左进入
			// setupdishwin.setAnimationStyle(android.R.style.Animation_Translucent);

			setupdishwin.showAtLocation(parent, Gravity.CENTER_VERTICAL, 0, 0);
		}

	}

	// 创建做法listview按下监听事件
	class cooklistviewListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			final Cookselectholder cookselectholder = (Cookselectholder) view
					.getTag();
			final int aaa;

			aaa = position;
			cookselectholder.cookitem4
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							cookselectholder.cookitem4.startchange();
							Toast.makeText(DishordersActivity.this,
									"点击了第" + aaa + "加1按钮", Toast.LENGTH_SHORT)
									.show();
						}
					});

			cookselectholder.cookitem5
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							cookselectholder.cookitem5.startchange();
							Toast.makeText(DishordersActivity.this,
									"点击了第" + aaa + "减1按钮", Toast.LENGTH_SHORT)
									.show();
						}
					});

		}
	}

	// 创建setupdishlistView按下监听事件
	class setupdishlistViewListener implements OnItemClickListener {

		private Dishpotlistholder dishpotlistholder = null;
		private float dishnum = 0;
		private String orderflag;
		private String dishid;

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			dishpotlistholder = (Dishpotlistholder) view.getTag();

			dishnum = Float.parseFloat(dishpotlistholder.dishitem3.getText()
					.toString());
			orderflag = dishpotlistholder.dishitem6.getText().toString();
			dishid = dishpotlistholder.dishid;
			dishpotlistholder.dishitem11
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (keydown) {
								return;
							}
                            try {
                            	keydown = true;
								dishnum = addclick(orderflag, dishid, dishnum);
								dishpotlistholder.dishitem11.startchange();
								if (!orderflag.equals("√")) {

									// showsetupdishlist(0);
									showdishlist();
									dishpotlistholder.dishitem3.setText(dishnum
											+ "");
								}
								keydown = false;
							} catch (Exception e) {
								// TODO: handle exception
								keydown = false;
							}
								

						}
					});

			dishpotlistholder.dishitem12
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							if (keydown) {
								return;
							}
							   try {
								   keydown = true;
									dishnum = delclick(orderflag, dishid, dishnum);
									dishpotlistholder.dishitem12.startchange();
									if (!orderflag.equals("√")) {
										if (dishnum == 0) {
											showsetupdishlist(1);
										} else {
											dishpotlistholder.dishitem3
													.setText(dishnum + "");
										}
										showdishlist();

									}
									keydown = false;
							} catch (Exception e) {
								// TODO: handle exception
								keydown = false;
							}
								
						}
					});

		}
	}

	// 加菜函数(未落单)
	private float addclick(String flag, final String dishid, float old_num) {
		if (db == null || !db.isOpen()) {
			db = DBHelper.getDatabase(getApplicationContext(), 1);
		}
		Cursor cursor = db.query("apkpos_orders_dishs",
				new String[] { "ifnull(max(dish_num),0) as aaa" },
				"orderid=? and dish_id=?", new String[] { orderid, dishid },
				null, null, null);
		while (cursor.moveToNext()) {
			old_num = cursor.getFloat(cursor.getColumnIndex("aaa"));

		}
		cursor.close();

		if (flag.equals("√")) {

			Builder builder = new Builder(this);
			String quitMsg = "已经传到厨房,确定要进行加菜操作吗？";
			builder.setMessage(quitMsg);
			builder.setTitle(string.dialog_title1);
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setPositiveButton(string.ok,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
							ApkDbUntils.changedishnum(db,
									getApplicationContext(), "add", 1, orderid,
									dishid);
							showsetupdishlist(1);
							showdishlist();
							Toast.makeText(DishordersActivity.this, "增加份量成功！",
									Toast.LENGTH_SHORT).show();
						}

					});
			builder.setNegativeButton(string.cancal,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}

					});

			builder.create().show();

		} else {

			ApkDbUntils.changedishnum(db, getApplicationContext(), "add", 1,
					orderid, dishid);
			showdishlist();
			// showsetupdishlist(0);

			Toast.makeText(DishordersActivity.this, "增加份量成功！",
					Toast.LENGTH_SHORT).show();

		}
		old_num = old_num + 1;
		return old_num;

	}

	// 减菜函数(已落单)
	private float delclick(String flag, final String dishid, float old_num) {
		if (db == null || !db.isOpen()) {
			db = DBHelper.getDatabase(getApplicationContext(), 1);
		}
		Cursor cursor = db.query("apkpos_orders_dishs",
				new String[] { "ifnull(max(dish_num),0) as aaa" },
				"orderid=? and dish_id=?", new String[] { orderid, dishid },
				null, null, null);
		while (cursor.moveToNext()) {
			old_num = cursor.getFloat(cursor.getColumnIndex("aaa"));

		}
		cursor.close();
		final float num = old_num - 1;
		if (num < 0) {
			Toast.makeText(DishordersActivity.this, "当前份量已经为零，无法减菜！",
					Toast.LENGTH_SHORT).show();
		} else {
			if (flag.equals("√")) {

				Builder builder = new Builder(this);
				String quitMsg = "已经传到厨房,确定要进行减菜操作吗？";
				builder.setMessage(quitMsg);
				builder.setTitle(string.dialog_title1);
				builder.setIcon(android.R.drawable.ic_dialog_info);
				builder.setPositiveButton(string.ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
								ApkDbUntils.changedishnum(db,
										getApplicationContext(), "del", 1,
										orderid, dishid);
								showsetupdishlist(1);
								showdishlist();
								Toast.makeText(DishordersActivity.this,
										"减少份量成功！", Toast.LENGTH_SHORT).show();

							}

						});

				builder.setNegativeButton(string.cancal,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}

						});

				builder.create().show();

			} else {

				if (old_num <= 1) {
					ApkDbUntils.deletedish(db, getApplicationContext(),
							orderid, dishid);
					// old_num = 0;
				} else {
					ApkDbUntils.changedishnum(db, getApplicationContext(),
							"del", 1, orderid, dishid);
					// old_num = old_num - 1;
					// showsetupdishlist(0);

					Toast.makeText(DishordersActivity.this, "减少份量成功！",
							Toast.LENGTH_SHORT).show();

				}
			}
		}

		old_num = old_num - 1;
		return old_num;

	}

	// 创建扩展菜品界面功能按钮事件
	class dishbtnListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			final int tag = (Integer) v.getTag();

			Rotate3dAnimation rotation = new Rotate3dAnimation(0, 90,
					v.getWidth() / 2.0f, v.getHeight() / 2.0f, 300.0f, false);
			rotation.setDuration(500);
			// rotation.setFillAfter(true);
			rotation.setInterpolator(new DecelerateInterpolator());
			v.setAnimation(rotation);
			v.startAnimation(rotation);
			rotation.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation animation) {
					// TODO Auto-generated method stub

					switch (tag) {
					case 1:
						if (setupdishwin != null) {

							ApkDbUntils.deletedishall(db,
									getApplicationContext(), orderid);
							showdishlist();
							setupdishwin.dismiss();
							setupdishwin = null;
						}
						break;
					case 2:
						if (setupdishwin != null) {

							ApkDbUntils.holdbill(db, getApplicationContext(),
									orderid);
							returnActivity();
						}
						break;
					case 3:
						if (setupdishwin != null) {
							orderlist = ApkDbUntils.checkbill(db,
									getApplicationContext());

						}
						break;
					case 4:// 设置按钮
						if (setupdishwin != null) {
							String str = dishcountchange.getText().toString();

							float d = Float.parseFloat(str);
							if (d < 0) {
								Toast.makeText(DishordersActivity.this,
										"折扣不能小于0,请重新设置！", Toast.LENGTH_SHORT)
										.show();
								dishcountchange.setText("0");
								ApkUntils.opensoftkeyboard(dishcountchange,
										powgridView, menuAdapter, 1);
							} else if (d > 100) {
								Toast.makeText(DishordersActivity.this,
										"折扣不能大于100,请重新设置！", Toast.LENGTH_SHORT)
										.show();
								dishcountchange.setText("100");
								ApkUntils.opensoftkeyboard(dishcountchange,
										powgridView, menuAdapter, 1);

							} else {
								ApkDbUntils.setupbill(db,
										getApplicationContext(), orderid, str);
								setupdishwin.dismiss();
								setupdishwin = null;
								showdishlist();
							}

						}
						break;

					case 10:
						if (setupdishwin != null) {
							// System.out.println("dddd" + tag);
							setupdishwin.dismiss();
							setupdishwin = null;
						}
						break;

					default:
						break;
					}
				}

			});

		}
	}

	// 创建做法选择窗体功能按钮
	class cookbtnListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int tag = (Integer) v.getTag();
			if (tag < 10) {
				Rotate3dAnimation rotation = new Rotate3dAnimation(0, 90,
						v.getWidth() / 2.0f, v.getHeight() / 2.0f, 300.0f,
						false);
				rotation.setDuration(500);
				// rotation.setFillAfter(true);
				rotation.setInterpolator(new DecelerateInterpolator());
				v.setAnimation(rotation);
				v.startAnimation(rotation);
				// v.clearAnimation();
			}

			switch (tag) {
			case 10:
				if (cookwin != null) {
					cookwin.dismiss();
				}
				break;
			case 1:

				break;
			default:
				break;
			}

		}

	}

	// 创建小类状态Listener
	class seconddishtypeListener implements OnItemClickListener {
		private Dishtypeholder2 tv;

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			// if (dishtypedown2 != position) {
			if (dishtypedown2 != -1) {

				if (dishtypedown2 <= parent.getChildCount() - 1) {

					tv = (Dishtypeholder2) parent.getChildAt(dishtypedown2)
							.getTag();

					tv.dishtype_btn2
							.setBackgroundResource(R.drawable.selector_btn_type2); // 恢复标签状态
				}

			}

			tv = (Dishtypeholder2) view.getTag();
			tv.dishtype_btn2.setBackgroundResource(R.drawable.btntype2b);
			typestate2 = tv.DclaVar;
			dishtypedown2 = position;
			showcainamelist();

			// }

		}

	}

	// 创建点菜Listener
	class cainameListener implements OnItemClickListener {
		private Dishholder tv;
		private float ORDL_VAR;
		private float DPRI_FLO;
		private String DNBR_VAR;
		private String DDET_VAR;
		private String PDET_VAR;
		private String PDET_VAR_IP;
		private String DNAM_VAR;
		private String order_mode;
		private int IS_PRINT;

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			tv = (Dishholder) view.getTag();
			order_mode = "";
			DNBR_VAR = tv.DNBR_VAR;
			DNAM_VAR = tv.DNAM_VAR;
			DPRI_FLO = tv.DPRI_FLO * 100;
			DDET_VAR = tv.DDET_VAR;
			ORDL_VAR = tv.ORDL_VAR;
			IS_PRINT = tv.IS_PRINT;
			PDET_VAR = tv.PDET_VAR;
			if (Apkglobal.getprint_ipmap() != null) {
				print_map = Apkglobal.getprint_ipmap();
			} else {
				print_map = ApkConfigdbUntils.getprint_ipmap(configdb,
						getApplicationContext());
				Apkglobal.setprint_ipmap(print_map);
			}

			PDET_VAR_IP = print_map.get(PDET_VAR);
			System.out.println("PDET_VAR_IP:" + PDET_VAR_IP);
			System.out
					.println("PDET_VAR_name:" + print_map.get(PDET_VAR + "N"));

			insertdish(DNBR_VAR, DNAM_VAR, 1, DPRI_FLO, DDET_VAR, ORDL_VAR,
					order_mode, PDET_VAR, PDET_VAR_IP, IS_PRINT);
			showdishlist();
		}

	}

	private void insertdish(String dnbr_var, String dnam_var, float dish_num,
			float dish_price, String dish_unit, float unit_id,
			String order_mode, String pdet_var, String pdet_var_ip, int is_print) {
		String dish_id = "";
		if (db == null || !db.isOpen()) {
			db = DBHelper.getDatabase(mcx, 0);
		}

		Cursor cursor = db.query("apkpos_orders_dishs",
				new String[] { "ifnull(max(dish_id),0)+1 as aaa" },
				"orderid=?", new String[] { orderid }, null, null, null);
		while (cursor.moveToNext()) {
			dish_id = cursor.getString(cursor.getColumnIndex("aaa"));

		}
		cursor.close();
		// System.out.println(dish_id);

		String date = dateformat.format(new java.util.Date());
		try {
			String sql = "insert into apkpos_orders_dishs(orderid,dish_id,dnbr_var,dnam_var,dish_num,"
					+ "dish_price,dish_unit,unit_id,free_state,dish_time,order_state,order_mode,dcy_name,"
					+ "dic_rate,svc_state,pdet_var,pdet_var_ip,IS_PRINT)"
					+ " values ('"
					+ orderid
					+ "',"
					+ dish_id
					+ ",'"
					+ dnbr_var
					+ "','"
					+ dnam_var
					+ "',"
					+ dish_num
					+ ","
					+ dish_price
					+ ",'"
					+ dish_unit
					+ "',"
					+ unit_id
					+ ",0,'"
					+ date
					+ "',0,'"
					+ order_mode
					+ "','"
					+ Apkglobal.getrealname()
					+ "',100,0"
					+ ",'"
					+ pdet_var
					+ "','"
					+ pdet_var_ip
					+ "',"
					+ is_print
					+ ")";

			execSQL(db,mcx,sql);
			
		} catch (SQLiteException e) {
			Log.e("apkpos_orders_dishs", "insert apkpos_orders_dishs error:"
					+ e.getMessage());
		}

	}

	// private List<Zuoflist> queryzuoflist(String orderid, String dish_id,
	// String subdish_id) {
	//
	// // TODO Auto-generated method stub
	// if (db == null || !db.isOpen()) {
	// db = DBHelper.getDatabase(getApplicationContext());
	// }
	// List<Zuoflist> data = new ArrayList<Zuoflist>();
	// String selection;
	// try {
	// OrderZuoflist orderzuoflist = new OrderZuoflist(
	// getApplicationContext());
	// selection = "orderid=? and dish_id=? and subdish_id=?";
	// String selectionArgs[] = { orderid, dish_id, subdish_id };
	// Cursor curSor = orderzuoflist.getCurSor(selection, selectionArgs);
	//
	// while (curSor.moveToNext()) {
	// data.add(orderzuoflist.CurSorToGasBean(curSor));
	//
	// }
	// curSor.close();
	// // System.out.println(data);
	//
	// } catch (SQLiteException e) {
	// Log.e("apkpos_orders_zuoflist",
	// "queryzuoflist  error:" + e.getMessage());
	// }
	//
	// return data;
	// }

	private void orderdishs(String orderid, String mode) {
		String sql="";
		try {
			if (db == null || !db.isOpen()) {
				db = DBHelper.getDatabase(mcx, 0);
			}
			Cursor cursor = db.query("apkpos_orders_dishs",
					new String[] { "dish_id" }, "orderid=? and order_state=0",
					new String[] { orderid }, null, null, null);
			int caiint = cursor.getCount();
		
			if (caiint > 0) {
                sql="  update  apkpos_orders_dishs set order_mode='"
						+ mode + "' where  order_state=0 and orderid='"
						+ orderid + "'  ";
               execSQL(db, mcx, sql);
             sql=" insert into apkpos_dishs_print select * from apkpos_orders_dishs where order_state=0 and is_print=1 and orderid='"
						+ orderid + "'  ";
			    execSQL(db, mcx, sql);
			 sql="  update  apkpos_orders_dishs set order_state=1,order_mode='"
						+ mode
						+ "' where  order_state=0 and orderid='"
						+ orderid + "'  ";
			  execSQL(db, mcx, sql);
			}
			cursor.close();
			
			if (db == null || !db.isOpen()) {
				db = DBHelper.getDatabase(mcx, 0);
			}
			cursor = db.query("apkpos_orders_subdishs",
					new String[] { "dish_id" }, "orderid=? and order_state=0",
					new String[] { orderid }, null, null, null);
			int subcaiint = cursor.getCount();
			if (subcaiint > 0) {
				if (db == null || !db.isOpen()) {
					db = DBHelper.getDatabase(getApplicationContext(), 1);
				}
				sql="  update  apkpos_orders_subdishs set order_mode='"
						+ mode + "' where  order_state=0 and orderid='"
						+ orderid + "'  ";
				 execSQL(db, mcx, sql);
				 sql=" insert into apkpos_subdishs_print select * from apkpos_orders_dishs where order_state=0 and is_print=1 and orderid='"
						+ orderid + "'  ";
				 execSQL(db, mcx, sql);
				 sql="  update  apkpos_orders_subdishs set order_state=1 where  order_state=0 and orderid='"
						+ orderid + "'  ";
				 execSQL(db, mcx, sql);
			}

			cursor.close();
			if (db == null || !db.isOpen()) {
				db = DBHelper.getDatabase(getApplicationContext(), 1);
			}
			if (caiint + subcaiint > 0) {
				cursor = db.query("apkpos_orders_print",
						new String[] { "table_num" }, "orderid=?",
						new String[] { orderid }, null, null, null);
				int orderint = cursor.getCount();
		
				if (orderint == 0) {

					sql=" insert into apkpos_orders_print select * from apkpos_orders_new where orderid='"
							+ orderid + "'  ";

				} else {
					sql="  update  apkpos_orders_print set order_state=0 where  orderid='"
							+ orderid + "'  ";
				 }
				 execSQL(db, mcx, sql);
				 
				Toast.makeText(DishordersActivity.this, "落单成功！",
						Toast.LENGTH_SHORT).show();
				return;
			} else {
				Toast.makeText(DishordersActivity.this, "当前没有菜需要下单！",
						Toast.LENGTH_SHORT).show();
				return;
			}

		} catch (SQLiteException e) {
			Toast.makeText(DishordersActivity.this, "落单失败！" + e.getMessage(),
					Toast.LENGTH_SHORT).show();
			Log.e("ORDERDISHS", "ORDERDISHS  error:" + e.getMessage());
			e.printStackTrace();
			return;
		}

	}

	private void paybill(String orderid, final String dish_total,
			final String close_time, final String order_pay,
			final String dic_charge, final String free_charge,
			final String svc_charge, final String extra_total,
			final String cashuser) {
		try {
			if (db == null || !db.isOpen()) {
				db = DBHelper.getDatabase(getApplicationContext(), 0);
			}

			Cursor cursor = db.query("apkpos_orders_dishs",
					new String[] { "dish_id" }, "orderid=?",
					new String[] { orderid }, null, null, null);
			int caiint = cursor.getCount();
			if (caiint == 0) {
				cursor.close();
				Toast.makeText(DishordersActivity.this, "当前没有点菜，没有结账必要！",
						Toast.LENGTH_SHORT).show();
                return;
			} else {
				if (db == null || !db.isOpen()) {
					db = DBHelper.getDatabase(getApplicationContext(), 0);
				}

				cursor = db.query("apkpos_orders_dishs",
						new String[] { "dish_id" },
						"orderid=? and order_state=0",
						new String[] { orderid }, null, null, null);
				caiint = cursor.getCount();
				if (caiint > 0) {
					cursor.close();
					Toast.makeText(DishordersActivity.this, "还有菜品没有落单，无法结账！",
							Toast.LENGTH_SHORT).show();
					return;

				} else {
					cursor.close();
					Builder builder = new Builder(this);
					String quitMsg = "温馨提示：请确认好当前埋单数据是否准确，以免产生纠纷！\n确定进行结账操作吗？";
					builder.setMessage(quitMsg);
					builder.setTitle(string.dialog_title1);
					builder.setIcon(android.R.drawable.ic_dialog_info);
					builder.setPositiveButton(string.ok,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
									updatemaid(dish_total, close_time,
											order_pay, dic_charge, free_charge,
											svc_charge, extra_total, cashuser);
								}

							});
					builder.setNegativeButton(string.cancal,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();

								}

							});

					builder.create().show();

				}
			}

		} catch (Exception e) {
			Toast.makeText(DishordersActivity.this, "结账失败！" + e.getMessage(),
					Toast.LENGTH_SHORT).show();
			Log.e("PAYBILL", "PAYBILL  error:" + e.getMessage());
			e.printStackTrace();
		}

	}

	private void updatemaid(String dish_total, String close_time,
			String order_pay, String dic_charge, String free_charge,
			String svc_charge, String extra_total, String cashuser) {

		String sqlinsert="";
		   
        String sqldelete = " delete from apkpos_orders_pay " +
        		"'  where  orderid='" + orderid + "'  ";
		if (paytype1>0) {
			 sqlinsert = " insert INTO apkpos_orders_pay (orderid,pay_typeid,pay_charge,original_amount,rate) VALUES" +
		        		"('" + orderid + "',1,"+paytype1+","+paytype1*0.01*rate1+","+rate1+") ";
				try {
					execSQL(db,mcx,sqlinsert);
			
				} catch (Exception e) {
					// TODO: handle exception
					db.execSQL(sqldelete);
					
					e.printStackTrace();
					return;	
				} 
		}
        
		if (paytype2>0) {
         sqlinsert = " insert INTO apkpos_orders_pay (orderid,pay_typeid,pay_charge,original_amount,rate) VALUES" +
        		"('" + orderid + "',2,"+paytype2+","+paytype2*0.01*rate2+","+rate2+") ";
     	try {
			execSQL(db,mcx,sqlinsert);
	
		} catch (Exception e) {
			// TODO: handle exception
			db.execSQL(sqldelete);
			
			e.printStackTrace();
			return;	
		}
		}
		if (paytype3>0) {
         sqlinsert =" insert INTO apkpos_orders_pay (orderid,pay_typeid,pay_charge,original_amount,rate) VALUES" +
        		"('" + orderid + "',3,"+paytype3+","+paytype3*0.01*rate3+","+rate3+") ";
     	try {
			execSQL(db,mcx,sqlinsert);
	
		} catch (Exception e) {
			// TODO: handle exception
			db.execSQL(sqldelete);
			
			e.printStackTrace();
			return;	
		}
		}
		
         String sqlinstate = "  update  apkpos_orders_new set dish_total=" + dish_total
 				+ ",room_state=7,close_time='" + close_time + "',order_pay="
 				+ order_pay + ",dic_charge=" + dic_charge + ",free_charge="
 				+ free_charge + ",svc_charge=" + svc_charge + ",extra_total="
 				+ extra_total + ",cashuser='" + cashuser
 				+ "'  where  orderid='" + orderid + "'  ";
      
         
	
		try {
			execSQL(db,mcx,sqlinstate);
	
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return;
		
		}

		if (ApkConstant.MAID_MODE == 0) {// 是否返回房台
			Intent intent = new Intent();
			intent.setClass(DishordersActivity.this, RoomtableActivity.class);
			startActivity(intent);
			ApkUntils.openActivityAnim(DishordersActivity.this, 0);      
			finish();
			return;
		}
		
	}

	// 创建大类状态Listener
	class firstdishtypeListener implements OnItemClickListener {
		private Dishtypeholder1 tv;

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			if (dishtypedown1 != position) {
				if (dishtypedown1 != -1) {
					tv = (Dishtypeholder1) parent.getChildAt(dishtypedown1)
							.getTag();
					tv.dishtype_btn1
							.setBackgroundResource(R.drawable.selector_btn_type1);
				}
				tv = (Dishtypeholder1) view.getTag();
				tv.dishtype_btn1.setBackgroundResource(R.drawable.btntype1b);
				typestate1 = tv.DclaVar;
				showdishtype2();
				dishtypedown1 = position;
			}

		}

	}

	// 更新菜品表信息
	private void updatedishlist() {

		if (db == null || !db.isOpen()) {
			db = DBHelper.getDatabase(getApplicationContext(), 0);
		}
		String args[] = { orderid };
		Cursor cursor;
		cursor = db.rawQuery(
				"select * from apkpos_orders_dishs where orderid=?", args);

		ArrayList<DishNew> data = new ArrayList<DishNew>();
		xiaoji = 0;
		zhekou = 0;
		yingshou = 0;
		extra_total = 0;

		while (cursor.moveToNext()) {
			DishNew dishnew = new DishNew();
			dishnew.setId(cursor.getPosition() + 1);
			dishnew.setOrderid(cursor.getString(cursor
					.getColumnIndex("orderid")));
			dishnew.setDnam_var(cursor.getString(cursor
					.getColumnIndex("dnam_var")));
			dishnew.setDish_unit(cursor.getString(cursor
					.getColumnIndex("dish_unit")));
			dishnew.setDish_time(cursor.getString(cursor
					.getColumnIndex("dish_time")));
			dishnew.setFree_state(cursor.getInt(cursor
					.getColumnIndex("free_state")));
			dishnew.setOrder_state(cursor.getInt(cursor
					.getColumnIndex("order_state")));
			dishnew.setOrder_mode(cursor.getString(cursor
					.getColumnIndex("order_mode")));
			dishnew.setDcy_name(cursor.getString(cursor
					.getColumnIndex("dcy_name")));
			dishnew.setCzy_name(cursor.getString(cursor
					.getColumnIndex("czy_name")));
			dishnew.setSvc_state(cursor.getInt(cursor
					.getColumnIndex("svc_state")));
			dishnew.setCook_content(cursor.getString(cursor
					.getColumnIndex("cook_content")));
			dishnew.setPdet_var(cursor.getString(cursor
					.getColumnIndex("pdet_var")));
			dishnew.setLbxh(cursor.getInt(cursor.getColumnIndex("lbxh")));
			dishnew.setLbname(cursor.getString(cursor.getColumnIndex("lbname")));

			dishnew.setDish_num(cursor.getInt(cursor.getColumnIndex("dish_num")));
			dishnew.setDish_price(cursor.getInt(cursor
					.getColumnIndex("dish_price")));
			dishnew.setDic_rate(cursor.getInt(cursor.getColumnIndex("dic_rate")));
			dishnew.setCook_extra(cursor.getInt(cursor
					.getColumnIndex("cook_extra")));
			dishnew.setOriginal_price(cursor.getInt(cursor
					.getColumnIndex("original_price")));

			dishnew.setDish_id(cursor.getInt(cursor.getColumnIndex("dish_id")));
			dishnew.setUnit_id(cursor.getInt(cursor.getColumnIndex("unit_id")));
			dishnew.setDnbr_var(cursor.getInt(cursor.getColumnIndex("dnbr_var")));

			data.add(dishnew);
			float dishnum = dishnew.getDish_num();
			float dprice = dishnew.getDish_price();
			float drate = dishnew.getDic_rate();
			float extra = dishnew.getCook_extra();

			int Free = dishnew.getFree_state();
			xiaoji = xiaoji + dishnum * dprice + extra;
			if (Free == 0) {
				zhekou = (float) (zhekou + (dishnum * dprice + extra)
						* (1 - 0.01 * drate));

			} else {
				zhekou = zhekou + dishnum * dprice + extra;
			}
			yingshou = xiaoji - zhekou;

		}
		cursor.close();
		// System.out.println(data);
		dishlist = data;

	}

	// 搜索框autosearch按下键盘监听器
	class autosearchselectClickListener implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			if (key_jiansuo) {
				return;
			}
		//	if (!key_jiansuo) {
				try {
					TextView id = (TextView) arg1.findViewById(R.id.listid);
					String str = id.getText().toString();
					String newstr = str.substring(str.indexOf("#") + 1,
							str.length());
					int i = Integer.parseInt(newstr);

					getinsertdish(i);

				} catch (Exception e) {
					// TODO: handle exception
					autosearch.setText("");
					autosearch.requestFocus();

				}

		//	}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}

	// 搜索框autosearch按下键盘监听器
	class autosearchItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			try {
				TextView tv = (TextView) arg1.findViewById(R.id.serchdishname);
				TextView id = (TextView) arg1.findViewById(R.id.listid);
				String str = id.getText().toString();
				String newstr = str.substring(str.indexOf("#") + 1,
						str.length());
				int i = Integer.parseInt(newstr);
				autosearch.setText(tv.getText().toString() + "");
				autosearch.setSelection((autosearch.getText().toString())
						.length());
				autosearch.setThreshold(100);
				getinsertdish(i);

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

		}

	}

	// 搜索框autosearch按下键盘监听器
	class autosearchOnTouchListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				int curX = (int) event.getX();
				if (curX > v.getWidth() - 38
						&& !TextUtils.isEmpty(autosearch.getText())) {
					autosearch.setText("");
					int cacheInputType = autosearch.getInputType();// backup the
																	// input
																	// type
					autosearch.setInputType(InputType.TYPE_NULL);// disable soft
																	// input
					autosearch.onTouchEvent(event);// call native handler
					autosearch.setInputType(cacheInputType);// restore input
															// type
					return true;// consume touch even
				}
				break;
			}
			return false;
		}

	}

	// 搜索框autosearch按下键盘监听器
	class autosearchOnkeyListener implements OnKeyListener {
		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub

			if (keyCode == KeyEvent.KEYCODE_ENTER) {
				// 当按下enter 时候关闭软键盘
				if (key_jiansuo) {
					InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
					// autosearch.setText("");

				} else {
					try {
						if (endterint > 0) {
							endterint = 0;
							if (endterstr.equals(autosearch.getText()
									.toString()) && endterstr.length() > 0) {
								String filterstr = endterstr;
								endterstr = "";
								CharSequence constraint = filterstr
										.subSequence(0, filterstr.length());
								Filter filter = dishAdapter.getFilter(); // 得到一个过滤器
								filter.filter(constraint); // 为该过滤器设置约束条件
								String str = dishAdapter.getItem(0).toString();
								String newstr = str.substring(
										str.indexOf("#") + 1, str.indexOf(","));
								int i = Integer.parseInt(newstr);
								getinsertdish(i);
								autosearch.setText("");
								filter.filter("");

							}

						} else {
							endterint++;
							endterstr = autosearch.getText().toString();
						}

					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}
				}

			}
			return false;
		}

	}

	private void getinsertdish(int i) {
		String order_mode = "";
		String DNBR_VAR = searchlist.get(i).getId() + "";
		String DNAM_VAR = searchlist.get(i).getDish_name();
		float DPRI_FLO = searchlist.get(i).getUnit_price();
		String DDET_VAR = searchlist.get(i).getUnit();
		float ORDL_VAR = searchlist.get(i).getInner_rank_id();
		String PDET_VAR = searchlist.get(i).getPrinter_name();
		String PDET_VAR_IP = searchlist.get(i).getPrinter_ip();
		int IS_PRINT = searchlist.get(i).getIs_print_item();

		insertdish(DNBR_VAR, DNAM_VAR, 1, DPRI_FLO, DDET_VAR, ORDL_VAR,
				order_mode, PDET_VAR, PDET_VAR_IP, IS_PRINT);
		showdishlist();
	}

	// 返回按钮监听器
	class returnButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {
		
				if (keydown) {
					return;
				}
				
				try {
					keydown = true;
					returnActivity();						
					keydown = false;					

			} catch (Exception e) {
				// TODO: handle exception
				keydown = false;
			}

		}

	}

	// 切换查询按钮监听器
	class searchButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			autosearch.setText("");
			int tag = (Integer) v.getTag();
			if (tag == 1) {
				if (!key_jiansuo) {
					key_jiansuo = true;
					autosearch.setHint("请输入菜品名或检索码");
					search.setBackgroundResource(R.drawable.selector_btn_search2);
					barcode.setBackgroundResource(R.drawable.selector_btn_barcode);
					autosearch.setInputType(InputType.TYPE_CLASS_TEXT);

					/*
					 * autosearch.setVisibility(2);
					 * autobarcode.setVisibility(1);
					 * autosearch.setFocusable(true);
					 * autosearch.setFocusableInTouchMode(true);
					 * autosearch.requestFocus();
					 */
				}

			} else {
				if (key_jiansuo) {
					key_jiansuo = false;
					autosearch.setHint("请刷条码");
					search.setBackgroundResource(R.drawable.selector_btn_search);
					barcode.setBackgroundResource(R.drawable.selector_btn_barcode2);
					InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(autosearch.getWindowToken(), 0);
					autosearch.setInputType(InputType.TYPE_NULL);
					autobarcode.setFocusableInTouchMode(true);
					autobarcode.requestFocus();

					/*
					 * autosearch.setVisibility(1);
					 * autobarcode.setVisibility(2);
					 * autobarcode.setFocusable(true);
					 * autobarcode.setFocusableInTouchMode(true);
					 * autobarcode.requestFocus();
					 */
				}

			}
		}

	}

	private void updateresponse() {
		configdb = ConfigDBHelper.getDatabase(getApplicationContext(),
				"shop_config.db", 0);

		// //////////////获取点菜信息
		if ((price_type == 0) && (Apkglobal.getcainamelist() != null)) {
			cainamelist = Apkglobal.getcainamelist();
		} else if ((price_type == 0) && (Apkglobal.getcainamelist1() != null)) {
			cainamelist = Apkglobal.getcainamelist1();
		} else {
			cainamelist = ApkConfigdbUntils.updateViewDianList(configdb,
					getApplicationContext(), price_type + "");
			if (price_type == 0) {
				Apkglobal.setcainamelist(cainamelist);
			} else {
				Apkglobal.setcainamelist1(cainamelist);
			}
		}

		searchlist = cainamelist;

		dishAdapter = buildserchAdapter(searchlist, R.layout.serchdishbtn);
		autosearch.setAdapter(dishAdapter); //
		dishAdapter.notifyDataSetChanged();
		typestate2 = cainamelist.get(0).getDish_class_id();
		showcainamelist();

		// //////////////获取做法
		if (Apkglobal.getmaketbllist() != null) {
			maketbllist = Apkglobal.getmaketbllist();

		} else {
			maketbllist = ApkConfigdbUntils.updatemakelist(configdb,
					getApplicationContext());
			Apkglobal.setmaketbllist(maketbllist);

		}
		searchmaketbllist = maketbllist;
		cooksearchAdapter = cookserchAdapter(searchmaketbllist,
				R.layout.serchdishbtn);

		// ////获取一级类别
		if (Apkglobal.getdishtypelist1() != null) {
			dishtypelist1 = Apkglobal.getdishtypelist1();
			typestate1 = dishtypelist1.get(0).getId();
			showdishtype1();
		} else {

			dishtypelist1 = ApkConfigdbUntils.updateClasslist(configdb,
					getApplicationContext(), 0);
			Apkglobal.setdishtypelist1(dishtypelist1);
			typestate1 = dishtypelist1.get(0).getId();
			showdishtype1();
		}

		// ////获取二级类别
		if (Apkglobal.getdishtypelist2() != null) {
			dishtypelist2 = Apkglobal.getdishtypelist2();
			showdishtype2();
		} else {
			dishtypelist2 = ApkConfigdbUntils.updateClasslist(configdb,
					getApplicationContext(), 1);
			Apkglobal.setdishtypelist2(dishtypelist2);
			showdishtype2();
		}
		configdb.close();


	}

	private void showdishlist() {
		updatedishlist();

		dishlistAdapter = new dishlistAdapter(this, dishlist);
		if (Apkglobal.getcurrentapiVersion() > 10) {
			dishlistView.setAdapter(dishlistAdapter);
		}
		if (dishlistAdapter.getCount() == 0) {
			ApkUntils.changeviewlayout(dishlistView,
					ApkUntils.convertPX2DIP(this, 492), 1, dishlistAdapter);
		} else {
			diahlistview_height = dishlist_heightdip
					* dishlistAdapter.getCount();
			ApkUntils.changeviewlayout(
					dishlistView,
					ApkUntils.convertPX2DIP(this,
							492 * ApkUntils.getPixelsintW(this)),
					diahlistview_height, dishlistAdapter);
		}

		changepay();
		// dishlistAdapter.notifyDataSetChanged();

	}

	// /////改变埋单数据显示
	private void changepay() {
		// xiaoji=dishlistAdapter.gettotal();
		// zhekou=dishlistAdapter.getcharge();

		pay_xj.setText(ApkUntils.convertFloat(xiaoji * 0.01 + "",
				ApkConstant.FLOAT_NUM));
		pay_zk.setText(ApkUntils.convertFloat(zhekou * 0.01 + "",
				ApkConstant.FLOAT_NUM));
		pay_ys.setText(ApkUntils.convertFloat(yingshou * 0.01 + "",
				ApkConstant.FLOAT_NUM));
		payedittext1.setText(ApkUntils.convertFloat(yingshou * 0.01 + "",
				ApkConstant.FLOAT_NUM));
		payedittext2.setText(ApkUntils.convertFloat(yingshou * 0.01 + "",
				ApkConstant.FLOAT_NUM));
		payedittext3.setText("0.0");
		payedittext4.setText("0.0");
		pay_zl.setText("0.0");

		/*
		 * pay_zk.setText(zhekou+""); pay_ys.setText((xiaoji-zhekou)+"");
		 */
	}

	private void showdishtype1() {
		dishtypeAdapter1 = new dishtype1Adapter(this, dishtypelist1);
		dishtypeGridView1.setNumColumns(dishtypeAdapter1.getCount());
		dishtypeview_width1 = (dishtypebtn_widthdp + dishtypeSpacingdip)
				* dishtypeAdapter1.getCount();
		if (Apkglobal.getcurrentapiVersion() > 10) {
			dishtypeGridView1.setAdapter(dishtypeAdapter1);
		}
		ApkUntils.changeviewlayout(dishtypeGridView1, dishtypeview_width1, 0,
				dishtypeAdapter1);

		if (dishtypeAdapter1.getCount() < 8) {
			SimpleAdapter1 = ApkUntils.ReadtestArray(this,
					8 - dishtypeAdapter1.getCount(), R.layout.dishtypebtn1,
					R.id.dishtype_btn1);
			dishtypeGridView3.setNumColumns(8 - dishtypeAdapter1.getCount());
			dishtypeview_width1 = (dishtypebtn_widthdp + dishtypeSpacingdip)
					* (8 - dishtypeAdapter1.getCount());
			if (Apkglobal.getcurrentapiVersion() > 10) {
				dishtypeGridView3.setAdapter(SimpleAdapter1);
			}
			ApkUntils.changeviewlayout(dishtypeGridView3, dishtypeview_width1,
					0, SimpleAdapter1);

			// SimpleAdapter1.notifyDataSetChanged();
		}

		// dishtypeAdapter1.notifyDataSetChanged();
	}

	private void showdishtype2() {

		dishtypeAdapter2 = builddishtypeAdapter2(dishtypelist2);
		dishtypeGridView2.setNumColumns(dishtypeAdapter2.getCount());
		dishtypeview_width1 = (dishtypebtn_widthdp + dishtypeSpacingdip)
				* dishtypeAdapter2.getCount();
		if (Apkglobal.getcurrentapiVersion() > 10) {
			dishtypeGridView2.setAdapter(dishtypeAdapter2);
		}
		if (dishtypeAdapter2.getCount() == 0) {
			ApkUntils.changeviewlayout(dishtypeGridView2, 1, 0,
					dishtypeAdapter2);
		} else {
			ApkUntils.changeviewlayout(dishtypeGridView2, dishtypeview_width1,
					0, dishtypeAdapter2);
		}

		if (dishtypeAdapter2.getCount() < 8) {
			SimpleAdapter2 = ApkUntils.ReadtestArray(this,
					8 - dishtypeAdapter2.getCount(), R.layout.dishtypebtn2,
					R.id.dishtype_btn2);
			dishtypeGridView4.setNumColumns(8 - dishtypeAdapter2.getCount());
			dishtypeview_width1 = (dishtypebtn_widthdp + dishtypeSpacingdip)
					* (8 - dishtypeAdapter2.getCount());
			if (Apkglobal.getcurrentapiVersion() > 10) {
				dishtypeGridView4.setAdapter(SimpleAdapter2);
			}
			ApkUntils.changeviewlayout(dishtypeGridView4, dishtypeview_width1,
					0, SimpleAdapter2);
			// SimpleAdapter2.notifyDataSetChanged();
		}

		// dishtypeAdapter2.notifyDataSetChanged();
	}

	private void showcainamelist() {

		cainameAdapter = buildCailistAdapter(cainamelist);
		dishview_height = dish_heightdip
				* (int) Math.ceil(cainameAdapter.getCount() / 5.0);
		if (Apkglobal.getcurrentapiVersion() > 10) {
			dishGridView.setAdapter(cainameAdapter);
		}
		ApkUntils.changeviewlayout(dishGridView, 0, dishview_height,
				cainameAdapter);
		// cainameAdapter.notifyDataSetChanged();
		dishSimpleAdapter = ApkUntils.ReadtestArray(this, 25, R.layout.dishbtn,
				R.id.dishname);
		dishview_height = dish_heightdip * 5;
		if (Apkglobal.getcurrentapiVersion() > 10) {
			dishGridView2.setAdapter(dishSimpleAdapter);
		}
		ApkUntils.changeviewlayout(dishGridView2, 0, dishview_height,
				dishSimpleAdapter);

		// dishSimpleAdapter.notifyDataSetChanged();
	}

	private SimpleAdapter buildserchAdapter(List<View_dian> list, int layout) {
		SimpleAdapter simpleAdapter = null;
		List<HashMap<String, String>> dishtypes = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < list.size(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("name", list.get(i).getDish_name());
			map.put("dnbr", list.get(i).getId() + "");
			map.put("ddet", list.get(i).getUnit());
			map.put("dpriflo", list.get(i).getUnit_price() * 0.01 + "");
			map.put("jsmm", list.get(i).getSearch_name());
			map.put("pdet", list.get(i).getPrinter_name());
			map.put("dcla", list.get(i).getDish_class_id() + "");
			map.put("id", "#" + i);
			map.put("serch", list.get(i).getSearch_name() + " "
					+ list.get(i).getDigit_search_id());
			dishtypes.add(map);
		}
		simpleAdapter = new SimpleAdapter(this, dishtypes, layout,
				new String[] { "name", "serch", "id" }, new int[] {
						R.id.serchdishname, R.id.search, R.id.listid });
		return simpleAdapter;
	}

	private SimpleAdapter cookserchAdapter(List<Make_tbl> list, int layout) {
		SimpleAdapter simpleAdapter = null;
		List<HashMap<String, String>> dishtypes = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < list.size(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("name", list.get(i).getCook_name());
			map.put("zuof_var", list.get(i).getId() + "");
			map.put("danw", list.get(i).getCook_unit());
			map.put("pricflo", list.get(i).getCook_price() + "");
			map.put("jsmm", list.get(i).getRetrieval_code());
			map.put("id", "#" + i);
			map.put("serch", list.get(i).getRetrieval_code() + " "
					+ list.get(i).getId());
			dishtypes.add(map);
		}
		simpleAdapter = new SimpleAdapter(this, dishtypes, layout,
				new String[] { "name", "serch", "id" }, new int[] {
						R.id.serchdishname, R.id.search, R.id.listid });
		return simpleAdapter;
	}

	private CailistAdapter buildCailistAdapter(List<View_dian> list) {
		if (typestate2 == -1) {
			cainameAdapter = new CailistAdapter(this, list);
		} else {
			List<View_dian> Adapterlist = new ArrayList<View_dian>();
			for (Iterator<View_dian> iterator = list.iterator(); iterator
					.hasNext();) {
				View_dian view_dian = (View_dian) iterator.next();
				if (view_dian.getDish_class_id() == typestate2) {
					Adapterlist.add(view_dian);
				}

			}
			cainameAdapter = new CailistAdapter(this, Adapterlist);
		}

		return cainameAdapter;

	}

	private void returnActivity() {
		
		try {
			if (db == null || !db.isOpen()) {
				db = DBHelper.getDatabase(getApplicationContext(),0);
			}
			String sql = "select *  from apkpos_orders_dishs where orderid='"
					+ orderid + "'  ";
			Cursor cursor= db.rawQuery(sql, null);
			if (cursor.getCount()==0) {	
				 sql = "  delete from  apkpos_orders_new where   orderid='"
						+ orderid + "'   ";
				 execSQL(db, mcx, sql);
				
			}
			else {
				sql="  update  apkpos_orders_new set dish_total="+xiaoji+" where  orderid='"
						+ orderid + "'  ;";
	
				sql=sql+"   update  apkpos_orders_new set room_state=3 where room_state<3 and orderid='"
						+ orderid + "' ";
				
			    execSQL(db, mcx, sql);				
			
			}
			cursor.close();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag, e.getMessage());
			e.printStackTrace();
		}
		
		Intent intent = new Intent();
		intent.setClass(DishordersActivity.this, RoomtableActivity.class);
		startActivity(intent);
		ApkUntils.openActivityAnim(DishordersActivity.this, 0);      
		finish();

	}

	private dishtype2Adapter builddishtypeAdapter2(List<Dish_class> list) {
		if (typestate1 == -1) {
			dishtypeAdapter2 = new dishtype2Adapter(this, list);
		} else {
			List<Dish_class> Adapterlist = new ArrayList<Dish_class>();
			for (Iterator<Dish_class> iterator = list.iterator(); iterator
					.hasNext();) {
				Dish_class dish_class = (Dish_class) iterator.next();
				if (dish_class.getFather_id() == typestate1) {
					Adapterlist.add(dish_class);
				}

			}
			dishtypeAdapter2 = new dishtype2Adapter(this, Adapterlist);
		}

		return dishtypeAdapter2;

	}

	// ////////////////////////
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		System.gc();
		super.onDestroy();
		// DataManager.instance().release();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updateresponse();

		showdishlist();
	}
	
	public void execSQL (SQLiteDatabase db, Context cx,String sql) {
		if (db == null || !db.isOpen()) {
			db = DBHelper.getDatabase(cx,1);
		}		
		db.execSQL(sql);
	}

}
